package com.chaoshi.controller;

import com.chaoshi.common.RateLimit;
import com.chaoshi.model.FruitRequest;
import com.chaoshi.model.ResultResponse;
import com.chaoshi.strategy.PriceStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/calculate")
public class CalculationController {

    @Autowired
    private Map<String, PriceStrategy> strategyMap;

    @PostMapping("/{customerType}")
    @RateLimit(permitsPerSecond = 5, timeout = 500) // 每秒最多5个请求，等待超时500ms
    public ResponseEntity<ResultResponse> calculate(
            @PathVariable String customerType,
            @Valid @RequestBody FruitRequest request
    ) {
        log.info("计算请求 - 类型: {}, 参数: {}", customerType, request);
        PriceStrategy strategy = strategyMap.get(customerType.toUpperCase());
        if (strategy == null) {
            throw new IllegalArgumentException("无效的客户类型");
        }

        BigDecimal total = strategy.calculate(
                request.getApple(),
                request.getStrawberry(),
                request.getMango()
        );
        log.debug("计算结果：{}", total);
        return ResponseEntity.ok(new ResultResponse(total, "CNY"));
    }
}
